#include "http_response.h"
#include "sys_socket.h"

namespace vmon_web
{
HttpResponse::HttpResponse(int sock):
    m_sock(sock), m_isHandled(false)
{
	addKeyword("Content-Type", "text/html; charset=utf-8");
}

HttpResponse::~HttpResponse()
{
}

int HttpResponse::send(const string& str)
{
    m_isHandled = true;
    return ::send(m_sock, str.c_str(), str.length(), 0 /*MSG_DONTWAIT*/);
}

int HttpResponse::send(void* buffer, unsigned int size)
{
    m_isHandled = true;
    return ::send(m_sock, (const char*)buffer, size, 0 /*MSG_DONTWAIT*/);
}

void HttpResponse::addKeyword(const string& key, const string& value)
{
	m_keywords[key] = value;
}

// code is something like "200 OK"
// XXX: this function is just a quick hack
int HttpResponse::sendHead(const string& code)
{
    int rc = 0;
	int bytes = 0;
    bytes = send(string("HTTP/1.1 ")+ code + "\r\n");
    if (bytes > 0) rc += (bytes = send("Server: vmon_web/0.0\r\n"));
    if (bytes > 0) rc += (bytes = send("Content-Type: text/html; charset=utf-8\r\n"));
	if (rc > 0)
	{
		map<string, string>::const_iterator iter = m_keywords.begin();
		while (iter != m_keywords.end())
		{
			if (bytes > 0) rc += (bytes = send(iter->first + ": " + iter->second + "\r\n"));
			++iter;
		}
	}
    if (bytes > 0) rc += (bytes = send("\r\n"));
    return rc;
}

bool HttpResponse::isHandled() const
{
    return m_isHandled;
}

}
